<template>
    <div class="container">
        <div class="options">
            <div @click="selectFirst = true" :class="{ 'selected': selectFirst }" class="option">已有账号，请绑定</div>
            <div @click="selectFirst = false" :class="{ 'selected': !selectFirst }" class="option">没有账号，请完善资料</div>
        </div>

        <div class="content">
            <template v-if="selectFirst">
                <el-form ref="bindRuleFormRef"
                    style="max-width: 550px; display: flex; flex-direction: column; align-items: center; margin: 0px auto 0;"
                    :model="bindRuleForm" status-icon :rules="bindRules" label-width="auto" class="demo-ruleForm">

                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model.trim="bindRuleForm.email" autocomplete="off" placeholder="请输入邮箱账号" />
                    </el-form-item>

                    <el-form-item label="密码" prop="pass">
                        <el-input v-model.trim="bindRuleForm.pass" type="password" autocomplete="off" placeholder="请输入密码" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="bindSubmitForm(bindRuleFormRef)">
                            立即绑定
                        </el-button>
                    </el-form-item>


                </el-form>
            </template>
            <template v-else>
                <el-form ref="createRuleFormRef"
                    style="max-width: 600px; display: flex; flex-direction: column; align-items: center; margin: 20px auto 0;"
                    :model="createRuleForm" status-icon :rules="createRules" label-width="auto" class="demo-ruleForm">
                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model.trim="createRuleForm.nickname" autocomplete="off" />
                    </el-form-item>

                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model.trim="createRuleForm.email" autocomplete="off" />
                    </el-form-item>

                    <el-form-item label="密码" prop="pass">
                        <el-input v-model.trim="createRuleForm.pass" type="password" autocomplete="off" />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="checkPass">
                        <el-input v-model.trim="createRuleForm.checkPass" type="password" autocomplete="off" />
                    </el-form-item>

                    <el-form-item label="验证码" prop="verifyCode">
                        <el-row>
                            <el-col :span="16">
                                <el-input v-model.trim="createRuleForm.verifyCode" style="width: 100px;" />
                            </el-col>
                            <el-col :span="8">
                                <el-button type="primary" plain @click="sendRegisterVerifyCode">{{ sendCodeButtonText
                                }}</el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="createSubmitForm(createRuleFormRef)">
                            注册
                        </el-button>
                    </el-form-item>
                </el-form>
            </template>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox, FormInstance, FormRules, ElNotification } from "element-plus";
import { wechatBindWithHasAccount, sendVerifyCode, register } from '@/api/user'
import { useTokenStore } from '@/stores/user';
import { useRouter } from "vue-router";


onMounted(() => {
    console.log("bind wechat_nickname");
    createRuleForm.nickname = store.wechat_nickname;
});

const router = useRouter();
const store = useTokenStore();


const selectFirst = ref(true);


const bindRuleFormRef = ref<FormInstance>();



const bindCheckEmail = (rule: any, value: any, callback: any) => {
    let reg =
        /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
    if (!reg.test(value)) {
        return callback(new Error("邮箱格式错误"));
    } else if (value.length > 50) {
        return callback(new Error("不支持超过50个字符的邮箱地址"));
    }
    callback();
};

const bindValidatePass = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输出密码"));
    } else {
        callback();
    }
};



const bindRuleForm = reactive({
    email: "",
    pass: ""
});

const bindRules = reactive<FormRules<typeof bindRuleForm>>({
    email: [{ validator: bindCheckEmail, trigger: "blur" }],
    pass: [{ validator: bindValidatePass, trigger: "blur" }],
});

const bindSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            console.log("submit!");


            try {
                const result = await wechatBindWithHasAccount(store.openid, bindRuleForm.email, bindRuleForm.pass);
                console.log('bind');
                store.login(result.data);
                await ElMessageBox.alert('绑定成功，前往首页', '绑定成功', {
                    confirmButtonText: '前往首页',
                })
                router.push("/ai_chat");

                //这个时候就让用户直接登录。所以要传来jwt。
            } catch (error) {
                console.log('bind error:' + error);
            }

        } else {
            console.log("error submit!");
        }
    });
};




const createRuleFormRef = ref<FormInstance>();

const createCheckNickname = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error("请输入昵称"));
    }
    setTimeout(() => {
        if (value.length < 3) {
            callback(new Error("昵称至少3个字符"));
        } else {
            if (value.length > 10) {
                callback(new Error("昵称最长10个个字符"));
            } else {
                callback();
            }
        }
    }, 1000);
};

const createCheckEmail = (rule: any, value: any, callback: any) => {
    let reg =
        /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
    if (!reg.test(value)) {
        return callback(new Error("邮箱格式错误"));
    } else if (value.length > 50) {
        return callback(new Error("不支持超过50个字符的邮箱地址"));
    }
    callback();
};

const createValidatePass = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输出密码"));
    } else {
        if (createRuleForm.checkPass !== "") {
            if (!createRuleFormRef.value) return;
            createRuleFormRef.value.validateField("checkPass");
        }
        callback();
    }
};
const createValidatePass2 = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请再次输出密码"));
    } else if (value !== createRuleForm.pass) {
        callback(new Error("Two inputs don't match!"));
    } else {
        callback();
    }
};

// 验证码应该全为数字
const createValidateVerifyCode = (rule: any, value: any, callback: any) => {
    if (value === "") {
        callback(new Error("请输入验证码"));
    } else if (!/^\d+$/.test(value)) {
        callback(new Error("验证码由数字组成"));
    } else if (value.length != 6) {
        callback(new Error("验证码为6位"));
    } else {
        callback();
    }
};



const createRuleForm = reactive({
    nickname: "",
    email: "",
    pass: "",
    checkPass: "",
    verifyCode: "",
});

const createRules = reactive<FormRules<typeof createRuleForm>>({
    nickname: [{ validator: createCheckNickname, trigger: "blur" }],
    email: [{ validator: createCheckEmail, trigger: "blur" }],
    pass: [{ validator: createValidatePass, trigger: "blur" }],
    checkPass: [{ validator: createValidatePass2, trigger: "blur" }],
    verifyCode: [{ validator: createValidateVerifyCode, trigger: "blur" }],
});

const createSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            console.log("submit!");


            try {
                const regResult = await register(createRuleForm.nickname, createRuleForm.email, createRuleForm.pass, createRuleForm.verifyCode)
                console.log("register");


                const bindResult = await wechatBindWithHasAccount(store.openid, createRuleForm.email, createRuleForm.pass);
                console.log('bind');
                store.login(bindResult.data);
                await ElMessageBox.alert('绑定成功，前往首页', '绑定成功', {
                    confirmButtonText: '前往首页',
                })
                router.push("/ai_chat");
            } catch (error) {
                console.log("error in wechat:" + error);
            }


        } else {
            console.log("error submit!");
        }
    });
};




let number = 60;
const disableSendCodeButton = ref(false);
let timer;
const sendCodeButtonText = ref('发送验证码');
let fn = function () {
    if (number <= 0) {
        sendCodeButtonText.value = '重新获取';
        disableSendCodeButton.value = false;
        number = 60;

        // 清除定时器
        clearInterval(timer);
    } else {
        disableSendCodeButton.value = true;
        sendCodeButtonText.value = --number + 's后重新获取'

    }
};

const sendRegisterVerifyCode = () => {
    if (createRuleForm.email != '') {
        if (!disableSendCodeButton.value) {
            sendVerifyCode(createRuleForm.email);

            fn();
            timer = setInterval(fn, 1000);
        }
    }
    else {
        ElNotification({
            title: '请先输入邮箱',
            message: '请先输入邮箱',
            type: 'error',
        })
    }

}


</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    /* 垂直居中 */
    width: 100%;
    /* 根据需要调整宽度 */
    margin: 20px 0;
    /* 上下外边距 */
}

.options {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中（对于行内元素其实不生效，但保持一致性）*/
    gap: 20px;
    /* 两个选项之间的间隔 */
}

.option {
    cursor: pointer;
    padding: 10px 20px;
}

.option.selected {
    border-color: red;
}

.option {
    position: relative;
    float: left;
    line-height: 34px;
    text-align: center;
    cursor: pointer;
    border-bottom: 4px solid #fff;
}

.content {
    width: 100%;
    /* 确保内容区域宽度与容器相同 */
    text-align: center;
    /* 文本居中 */
    margin-top: 20px;
    /* 与上面的选项保持一定距离 */
}

</style>